 # -*- coding: utf-8 -*-
import uuid
import logging
import requests
import json
from datetime import datetime, timedelta
from urllib.parse import urlencode, parse_qs
from django.utils import timezone
from django.conf import settings
from django.core.cache import cache
import urllib3
from app.models import AmazonStore  # 修正导入路径
from app.intereface_amazon.amazon_config import SP_API_CREDENTIALS  # 修正导入路径

logger = logging.getLogger(__name__)

class AmazonOAuthService:
    """Amazon SP-API OAuth 2.0 授权服务 - 严格按照Amazon协议实现"""
    
    # Amazon LWA OAuth 端点
    LWA_AUTH_URL = "https://sellercentral.amazon.com/apps/authorize/consent"
    LWA_TOKEN_URL = "https://api.amazon.com/auth/o2/token"

    # 请参照亚马逊，给出给出ebay平台的授权信息



    # SP-API 端点
    SP_API_ENDPOINTS = {
        'NA': 'https://sellingpartnerapi-na.amazon.com',
        'EU': 'https://sellingpartnerapi-eu.amazon.com', 
        'FE': 'https://sellingpartnerapi-fe.amazon.com'
    }
    
    def __init__(self):
        """初始化Amazon OAuth服务"""
        # 从配置获取应用信息
        # self.client_id = SP_API_CREDENTIALS['lwa_client_id']
        # self.client_secret = SP_API_CREDENTIALS['lwa_client_secret']
        self.app_id = 'amzn1.application-oa2-client.20250605-000000'
        self.app_secret = 'amzn1.application-oa2-client.20250605-000000'

    def get_ebay_auth_url(self, client_id, redirect_uri, state, scopes=None):
        params = {
            'client_id': client_id,
            'response_type': 'code',
            'redirect_uri': redirect_uri,
            'scope': ' '.join(self.EBAY_SCOPES),
            'state': state
        }
        auth_url= f"{self.EBAY_AUTH_URL}?{urllib3.parse.urlencode(params)}"  
        cache.set(f"amazon_oauth_state_{state}", {
            'redirect_uri': redirect_uri,
            'created_at': timezone.now().isoformat(),
            'scopes': scopes
        }, timeout=1800)  # 30分钟过期
        
        logger.info(f"Generated Amazon auth URL for state: {state}")
        return auth_url, state
    def generate_auth_url_foramazon(self, redirect_uri, state=None,store=None, scopes=None):
        """
        生成Amazon授权URL
        
        Args:
            redirect_uri: 回调地址
            state: 状态参数，用于防CSRF攻击
            scopes: 权限范围，默认为SP-API权限
            
        Returns:
            tuple: (授权URL, state值)
        """
        if not state:
            state = str(uuid.uuid4())
            
        if not scopes:
            # Amazon SP-API 默认权限
            scopes = [
                'sellingpartnerapi::notifications',
                'sellingpartnerapi::migration'
            ]
        
        # 构建授权参数
        auth_params = {
            'application_id': store.app_config.client_id,
            # 'response_type': 'code',
            'redirect_uri': redirect_uri,
            'state': state,
            'version': 'beta'
        }
        
        # 生成完整的授权URL
        # auth_url = f"{self.LWA_AUTH_URL}?{urlencode(auth_params)}"
        auth_url = f"{self.LWA_AUTH_URL}?application_id={store.app_config.client_id}&redirect_uri={redirect_uri}&state={state}&version=beta"
        
        cache.set(f"amazon_oauth_state_{state}", {
            'redirect_uri': redirect_uri,
            'created_at': timezone.now().isoformat(),
            'scopes': scopes
        }, timeout=1800)  # 30分钟过期
        
        logger.info(f"Generated Amazon auth URL for state: {state}")
        return auth_url, state
    
    def exchange_code_for_tokens(self, code, redirect_uri, state=None):
        """
        使用授权码换取访问令牌
        
        Args:
            code: 授权码
            redirect_uri: 回调地址
            state: 状态参数
            
        Returns:
            dict: 包含访问令牌和刷新令牌的字典
        """
        # 验证state参数
        if state:
            cached_state = cache.get(f"amazon_oauth_state_{state}")
            if not cached_state:
                raise ValueError("Invalid or expired state parameter")
            
            if cached_state['redirect_uri'] != redirect_uri:
                raise ValueError("Redirect URI mismatch")
        
        # 构建token请求参数
        token_params = {
            'grant_type': 'authorization_code',
            'code': code,
            'redirect_uri': redirect_uri,
            'client_id': self.client_id,
            'client_secret': self.client_secret,
        }
        
        # 发送token请求
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'User-Agent': 'YourAppName/1.0'  # Amazon建议添加User-Agent
        }
        
        try:
            response = requests.post(
                self.LWA_TOKEN_URL,
                data=token_params,
                headers=headers,
                timeout=30
            )
            response.raise_for_status()
            
            token_data = response.json()
            
            # 检查响应
            if 'access_token' not in token_data:
                raise ValueError("No access token in response")
            
            # 计算过期时间
            expires_in = token_data.get('expires_in', 3600)
            expires_at = timezone.now() + timedelta(seconds=expires_in)
            
            # 整理返回数据
            result = {
                'access_token': token_data['access_token'],
                'refresh_token': token_data.get('refresh_token'),
                'token_type': token_data.get('token_type', 'bearer'),
                'expires_in': expires_in,
                'expires_at': expires_at,
                'scope': token_data.get('scope', ''),
            }
            
            # 清理缓存的state
            if state:
                cache.delete(f"amazon_oauth_state_{state}")
            
            logger.info("Successfully exchanged authorization code for tokens")
            return result
            
        except requests.exceptions.RequestException as e:
            logger.error(f"Token exchange failed: {str(e)}")
            raise ValueError(f"Token exchange failed: {str(e)}")
        except (ValueError, KeyError) as e:
            logger.error(f"Invalid token response: {str(e)}")
            raise ValueError(f"Invalid token response: {str(e)}")
    
    def refresh_access_token(self, refresh_token):
        """
        使用刷新令牌获取新的访问令牌
        
        Args:
            refresh_token: 刷新令牌
            
        Returns:
            dict: 包含新访问令牌的字典
        """
        token_params = {
            'grant_type': 'refresh_token',
            'refresh_token': refresh_token,
            'client_id': self.client_id,
            'client_secret': self.client_secret,
        }
        
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded',
            'User-Agent': 'YourAppName/1.0'
        }
        
        try:
            response = requests.post(
                self.LWA_TOKEN_URL,
                data=token_params,
                headers=headers,
                timeout=30
            )
            response.raise_for_status()
            
            token_data = response.json()
            
            if 'access_token' not in token_data:
                raise ValueError("No access token in response")
            
            # 计算过期时间
            expires_in = token_data.get('expires_in', 3600)
            expires_at = timezone.now() + timedelta(seconds=expires_in)
            
            result = {
                'access_token': token_data['access_token'],
                'token_type': token_data.get('token_type', 'bearer'),
                'expires_in': expires_in,
                'expires_at': expires_at,
                'scope': token_data.get('scope', ''),
            }
            
            # 如果返回了新的刷新令牌，也包含进来
            if 'refresh_token' in token_data:
                result['refresh_token'] = token_data['refresh_token']
            
            logger.info("Successfully refreshed access token")
            return result
            
        except requests.exceptions.RequestException as e:
            logger.error(f"Token refresh failed: {str(e)}")
            raise ValueError(f"Token refresh failed: {str(e)}")
        except (ValueError, KeyError) as e:
            logger.error(f"Invalid token response: {str(e)}")
            raise ValueError(f"Invalid token response: {str(e)}")
    
    def get_seller_info(self, access_token, region='NA'):
        """
        获取卖家信息
        
        Args:
            access_token: 访问令牌
            region: 区域
            
        Returns:
            dict: 卖家信息
        """
        endpoint = self.SP_API_ENDPOINTS.get(region, self.SP_API_ENDPOINTS['NA'])
        url = f"{endpoint}/sellers/v1/marketplaceParticipations"
        
        headers = {
            'Authorization': f'Bearer {access_token}',
            'x-amz-access-token': access_token,
            'Content-Type': 'application/json',
            'User-Agent': 'YourAppName/1.0'
        }
        
        try:
            response = requests.get(url, headers=headers, timeout=30)
            response.raise_for_status()
            
            return response.json()
            
        except requests.exceptions.RequestException as e:
            logger.error(f"Failed to get seller info: {str(e)}")
            raise ValueError(f"Failed to get seller info: {str(e)}")
    
    def save_store_credentials(self, seller_id, credentials_data, user_id=None):
        """
        保存店铺认证信息
        
        Args:
            seller_id: 卖家ID
            credentials_data: 认证数据
            user_id: 用户ID
            
        Returns:
            AmazonStore: 店铺对象
        """
        try:
            # 查找或创建店铺记录
            store, created = AmazonStore.objects.get_or_create(
                seller_id=seller_id,
                defaults={
                    'store_name': f'Amazon Store {seller_id}',
                    'access_token': credentials_data['access_token'],
                    'refresh_token': credentials_data.get('refresh_token'),
                    'token_type': credentials_data.get('token_type', 'bearer'),
                    'expires_at': credentials_data['expires_at'],
                    'scope': credentials_data.get('scope', ''),
                    'is_active': True,
                    'user_id': user_id,
                }
            )
            
            # 如果店铺已存在，更新认证信息
            if not created:
                store.access_token = credentials_data['access_token']
                if credentials_data.get('refresh_token'):
                    store.refresh_token = credentials_data['refresh_token']
                store.token_type = credentials_data.get('token_type', 'bearer')
                store.expires_at = credentials_data['expires_at']
                store.scope = credentials_data.get('scope', '')
                store.is_active = True
                store.save()
            
            logger.info(f"Successfully saved credentials for seller: {seller_id}")
            return store
            
        except Exception as e:
            logger.error(f"Failed to save store credentials: {str(e)}")
            raise ValueError(f"Failed to save store credentials: {str(e)}")